﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Diagnostics;

namespace iPhoneUI.Widgets
{
    public class BitmapButton : ButtonWidget
    {
        private Bitmap m_image;
        private Bitmap m_imageDown;

        public BitmapButton()
        {
        }

        protected override void OnDispose()
        {
            m_image.SafeDispose();
            m_imageDown.SafeDispose();

            base.OnDispose();
        }

        public Bitmap Image
        {
            get { return m_image; }
            set
            {
                m_image.SafeDispose();

                m_image = value;
                Size = Owner.ScaleSize(m_image.Size);
            }
        }

        public Bitmap ImageDown
        {
            get
            {
                return m_imageDown;
            }
            set
            {
                m_imageDown.SafeDispose();

                m_imageDown = value;
            }
        }

        protected override void OnDraw(Canvas canvas, Rectangle clipBounds)
        {
            Color color = GetTransparentColor(m_image);
            using (ImageAttributes attrib = new ImageAttributes())
            {
                attrib.SetColorKey(color, color);

                if (!Pushed || m_imageDown == null)
                    canvas.DrawImage(m_image, ClientArea, 0, 0, m_image.Width, m_image.Height, attrib);
                else
                    canvas.DrawImage(m_imageDown, ClientArea, 0, 0, m_image.Width, m_image.Height, attrib);
            }

            base.OnDraw(canvas, clipBounds);
        }

        private static Color GetTransparentColor(Bitmap image)
        {
            return image.GetPixel(0, 0);
        }
    }
}
